package com.itheima.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.itheima.pay.config.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
/**
 * @Description:
 * @Version: V1.0
 */
@RestController
public class PayController {
    @Autowired
    AlipayConfig alipayConfig;

    @GetMapping("/alipaytest")
    public String alipaytest(String orderNo) throws IOException {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getURL(),
                alipayConfig.getAPPID(), alipayConfig.getRSA_PRIVATE_KEY(),
                alipayConfig.getFORMAT(), alipayConfig.getCHARSET(),
                alipayConfig.getALIPAY_PUBLIC_KEY(), alipayConfig.getSIGNTYPE());
        //获得初始化的AlipayClient
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setReturnUrl("url");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);  //交易单号 20220817010101003
        bizContent.put("total_amount", 0.01); //交易金额 单位：元
        bizContent.put("subject", "餐掌柜-餐饮消费"); //支付备注

        request.setBizContent(bizContent.toJSONString());
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                System.out.println(response.getQrCode());
                return response.getQrCode();
            } else {
                System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        return "OK";
    }

    @GetMapping("query")
    public String query(String orderNo) {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getURL(),
                alipayConfig.getAPPID(), alipayConfig.getRSA_PRIVATE_KEY(),
                alipayConfig.getFORMAT(), alipayConfig.getCHARSET(),
                alipayConfig.getALIPAY_PUBLIC_KEY(), alipayConfig.getSIGNTYPE());


        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);  //交易单号
        request.setBizContent(bizContent.toJSONString());

        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);

            //交易状态：
            // WAIT_BUYER_PAY（交易创建，等待买家付款）、
            // TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、
            // TRADE_SUCCESS（交易支付成功）、
            // TRADE_FINISHED（交易结束，不可退款）
            if (response.isSuccess()) {
                System.out.println("查询成功");
                System.out.println(response);
                return response.getTradeStatus();
            }


        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return "OK";
    }

    @GetMapping("refund")
    public AlipayTradeRefundResponse refund(String orderNo, String refundNo) {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getURL(),
                alipayConfig.getAPPID(), alipayConfig.getRSA_PRIVATE_KEY(),
                alipayConfig.getFORMAT(), alipayConfig.getCHARSET(),
                alipayConfig.getALIPAY_PUBLIC_KEY(), alipayConfig.getSIGNTYPE());


        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);  //交易单号
        bizContent.put("refund_amount", "0.01");  //退款金额 单位：元
        bizContent.put("refund_reason", "菜品有毒");
        bizContent.put("out_request_no", refundNo);

        request.setBizContent(bizContent.toJSONString());

        try {
            AlipayTradeRefundResponse response = alipayClient.execute(request);

            if (response.isSuccess()) {
                System.out.println("受理成功");
                System.out.println(response.toString());
                return response;
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return null;
    }
}
